package com.huaxin.hxcloud.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.design.widget.AppBarLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.huaxin.common.BaseActivity;
import com.huaxin.common.Constants;
import com.huaxin.common.Entity.CheckPoint;
import com.huaxin.common.Entity.DataValuesBean;
import com.huaxin.common.Entity.SmallDeviceDTO;
import com.huaxin.common.Entity.SmallDeviceInfo;
import com.huaxin.common.Entity.SubDevice;
import com.huaxin.common.tools.HxTransmitRequestHelper;
import com.huaxin.common.tts.Constant;
import com.huaxin.common.utils.ToastUtil;
import com.huaxin.common.view.BottomSheetDialogOther;
import com.huaxin.hxcloud.R;
import com.huaxindata.im.main.manager.UserManager;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Administrator on 2016/12/29.
 */

public class SmallDeviceInfoActivity extends BaseActivity {


    MyAdapter _adapter;
    @BindView(R.id.iv_device)
    ImageView    ivDevice;
    @BindView(R.id.tv_name)
    TextView     tvName;
    @BindView(R.id.tv_brand)
    TextView     tvBrand;
    @BindView(R.id.tv_model)
    TextView     tvModel;
    @BindView(R.id.tv_check_cycle)
    TextView     tvCheckCycle;
    @BindView(R.id.toolbar)
    Toolbar      toolbar;
    @BindView(R.id.more)
    TextView     more;
    @BindView(R.id.appbar)
    AppBarLayout appbar;
    @BindView(R.id.list_view)
    RecyclerView listView;
    @BindView(R.id.tv_target)
    TextView     tv_tartget;
    @BindView(R.id.btn_device_info)
    Button       btn_device_info;
    private List _datas = new ArrayList<>();
    private SmallDeviceDTO        smallDevice;
    private String                _deviceCode;
    private String                bigDeviceName;
    private List<SmallDeviceInfo> deviceInfos;


    public static void start(Context context, SubDevice subDevice, String bigDeviceName) {
        Intent intent = new Intent(context, SmallDeviceInfoActivity.class);
        intent.putExtra(Constants.IK_DEVICE_CODE, subDevice.getSubDeviceCode());
        intent.putExtra(Constants.IK_DEVICE_NAME, bigDeviceName);
        context.startActivity(intent);
    }

    @Override
    protected void getBundleExtras(Bundle extras) {
        super.getBundleExtras(extras);
        _deviceCode = extras.getString(Constants.IK_DEVICE_CODE);
        bigDeviceName = extras.getString(Constants.IK_DEVICE_NAME);
        //        _deviceCode = "2";
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_check_record;
    }

    @Override
    protected int getLoadFrameId() {
        return R.id.content;
    }

    @Override
    public void initView() {
        super.initView();
        setSupportActionBar(toolbar);
        _adapter = new MyAdapter();
        listView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL,
                false));
        listView.setAdapter(_adapter);
        updateView();
        //力鼎 自设备指标
        if (Constant.LDOrgcodeFirst.equals(UserManager.getFirstOrgCode())) {
            tv_tartget.setVisibility(View.VISIBLE);
        } else {
            tv_tartget.setVisibility(View.GONE);
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.HONEYCOMB)
    @OnClick({R.id.more, R.id.tv_target, R.id.btn_device_info})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.more:
                RepairRecordActivity.start(this, smallDevice.getDeviceCode());
                break;
            case R.id.tv_target:
                //查看指标数据
                ArrayList<DataValuesBean> targetData = (ArrayList<DataValuesBean>) smallDevice.getZishebei();
                if (smallDevice != null && targetData != null && targetData.size() > 0) {
                    Intent intent = new Intent(SmallDeviceInfoActivity.this, StationRealDataActivity.class);
                    intent.putExtra(Constants.IK_DEVICE_CODE, smallDevice.getDeviceCode());
                    intent.putExtra("smalldeviecdata", 1);
                    intent.putParcelableArrayListExtra(Constants.IK_TARGET_DATA, targetData);
                    startActivity(intent);
                } else {
                    ToastUtil.showToast("该设备暂无相关指标");
                }

                break;
            case R.id.btn_device_info:
                //弹出底部弹框查看设备信息
                new BottomSheetDialogOther(this, deviceInfos).show(getFragmentManager(), "BottomSheetDiologOther");
                break;
        }
    }

    @Override
    public void requestData() {
        ApiRequestData(LOADING);
    }

    public void ApiRequestData(int status) {
        updateLoadStatus(status);
        Call<SmallDeviceDTO> call = HxTransmitRequestHelper.getRequestApi().smallDeviceInfo(_deviceCode);
        autoClose(call);
        call.enqueue(new Callback<SmallDeviceDTO>() {
            @Override
            public void onResponse(Call<SmallDeviceDTO> call, Response<SmallDeviceDTO> response) {
                SmallDeviceDTO smallDevice = response.body();
                if (smallDevice != null && smallDevice.isSuccessful()) {
                    updateLoadStatus(LOAD_SUCCESS);
                    deviceInfos = smallDevice.getDeviceInfo();
                    //华骐 查看设备详细信息
                    if (Constant.HQOrgcodeFirst.equals(UserManager.getFirstOrgCode()) && deviceInfos != null && deviceInfos.size() > 0) {
                        btn_device_info.setVisibility(View.VISIBLE);
                    } else {
                        btn_device_info.setVisibility(View.GONE);
                    }
                    List<CheckPoint> devices = smallDevice.getItemList();
                    if (devices == null || devices.size() == 0) {
                        // updateLoadStatus(LOAD_NO_DATA);
                        _datas.add(Constants.EMPTY_VIEW);
                    } else {

                        _datas.addAll(devices);
                    }
                    _adapter.notifyDataSetChanged();
                    SmallDeviceInfoActivity.this.smallDevice = smallDevice;

                    updateView();

                } else {
                    updateLoadStatus(LOAD_ERROR);
                    ToastUtil.showToast(smallDevice.getMsg());
                }

            }

            @Override
            public void onFailure(Call<SmallDeviceDTO> call, Throwable t) {
                updateLoadStatus(LOAD_FAILURE);
            }
        });
    }

    private void updateView() {
        if (smallDevice != null) {
            toolbar.setTitle(smallDevice.getDeviceName());
            if (smallDevice.getImgUrl() != null && !smallDevice.getImgUrl().isEmpty()) {
                loadNetImg(ivDevice, smallDevice.getImgUrl().get(0).getImgUrl());
            }
            loadText("设备类型 ", tvName, "子设备", "暂无");
            loadText("品牌 ", tvBrand, smallDevice.getBrand(), "暂无");
            loadText("点检周期 ", tvCheckCycle, smallDevice.getCheckPointCycle() + "天", "暂无");
            loadText("型号 ", tvModel, smallDevice.getModel(), "暂无");
        }
    }


    protected class MyAdapter extends RecyclerView.Adapter {

        private static final int ITEM_EMPTY       = 0x00;
        private static final int ITEM_TYPE_RECORD = 0x01;


        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            if (viewType == ITEM_EMPTY) {
                return new EmptyHolder(mInflater.inflate(R.layout.item_empty_nodata_center, parent, false));
            } else if (viewType == ITEM_TYPE_RECORD) {
                return new MyViewHolder(mInflater.inflate(R.layout.item_check_record, parent,
                        false));
            }
            return null;
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
            if (getItemViewType(position) == ITEM_TYPE_RECORD) {
                ((MyViewHolder) holder).update(position);
            }
        }

        @Override
        public int getItemViewType(int position) {
            Object data = _datas.get(position);
            if (data instanceof CheckPoint) {
                return ITEM_TYPE_RECORD;
            }
            return ITEM_EMPTY;
        }


        @Override
        public int getItemCount() {
            return _datas == null ? 0 : _datas.size();
        }


        public class EmptyHolder extends RecyclerView.ViewHolder {
            View itemView;

            public EmptyHolder(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
                autoClose(ButterKnife.bind(this, itemView));
                this.itemView = itemView;
                //ImageMarkUtil.setWaterMarkTextBg(itemView,ArrangeTaskHistoryActivity.this,"暂无数据");
            }

            public void update(int position) {


            }
        }

        public class MyViewHolder extends RecyclerView.ViewHolder {
            @BindView(R.id.tv_name)
            TextView     tvName;
            @BindView(R.id.tv_des)
            TextView     tvDes;
            @BindView(R.id.ls_img)
            RecyclerView lsImg;
            @BindView(R.id.tv_remark)
            TextView     tvRemark;
            @BindView(R.id.tv_date)
            TextView     tvDate;
            @BindView(R.id.iv_state)
            ImageView    IvState;
            @BindView(R.id.tv_workman)
            TextView     tv_workman;

            ImgAdapter   iAdapter;
            List<String> imgs;
            int          position;
            View         itemView;

            public MyViewHolder(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
                this.itemView = itemView;
                imgs = new ArrayList<>();
                iAdapter = new ImgAdapter();
                lsImg.setLayoutManager(new LinearLayoutManager(SmallDeviceInfoActivity.this,
                        LinearLayoutManager.HORIZONTAL, false));
                lsImg.setAdapter(iAdapter);
            }


            public void update(int position) {
                this.position = position;
                CheckPoint checkPoint = (CheckPoint) _datas.get(position);
                loadText("点检项：", tvName, checkPoint.getName());
                loadText("描述：", tvDes, checkPoint.getDescription());
                if (checkPoint.getCheckFinishDate() == 0){
                    tvDate.setVisibility(View.GONE);
                }else{
                    loadText(tvDate, dateFormat(checkPoint.getCheckFinishDate(), "yyyy-MM-dd"));
                }
                loadText("备注：", tvRemark, checkPoint.getRemark());
                loadTextColon(tv_workman, "负责人", checkPoint.getXjWorkerName());
                imgs.clear();
                if (checkPoint.getImageName() == null || checkPoint.getImageName().isEmpty()) {
                    lsImg.setVisibility(View.GONE);
                } else {
                    lsImg.setVisibility(View.VISIBLE);
                    imgs.addAll(checkPoint.getImageName());
                }
                iAdapter.setImages(imgs);
                iAdapter.notifyDataSetChanged();
                loadState(checkPoint.getCheckState());
            }

            public void loadState(Integer state) {
                switch (state) {
                    case 0:
                        IvState.setImageResource(R.drawable.icon_state_normal);

                        break;
                    case 1:
                        IvState.setImageResource(R.drawable.icon_state_error);

                        break;
                    case 2:
                        IvState.setImageResource(R.drawable.icon_state_stop);

                        break;
                    default:
                        break;
                }
            }

        }
    }


    protected class ImgAdapter extends RecyclerView.Adapter {
        List<String> mImages;
        private static final int ITEM_TYPE_EMPTY   = 0x02;
        private static final int ITEM_TYPE_IMG     = 0x01;
        private static final int ITEM_TYPE_DEFAULT = 0x00;

        public void setImages(List<String> images) {
            this.mImages = images;
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            if (viewType == ITEM_TYPE_IMG) {
                return new ImgHolder(mInflater.inflate(R.layout.item_h_image, parent, false));
            } else if (viewType == ITEM_TYPE_EMPTY) {
                return new EmptyHolder(mInflater.inflate(R.layout.item_empty3, parent, false));
            }
            return null;

        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
            if (getItemViewType(position) == ITEM_TYPE_IMG) {
                ((ImgHolder) holder).update(position);
            } else if (getItemViewType(position) == ITEM_TYPE_EMPTY) {
                ((EmptyHolder) holder).update(position);
            }

        }

        @Override
        public int getItemViewType(int position) {
            Object data = mImages.get(position);
            if (data.equals(Constants.EMPTY_VIEW)) {
                return ITEM_TYPE_EMPTY;
            }
            return ITEM_TYPE_IMG;
        }

        @Override
        public int getItemCount() {
            return mImages == null ? 0 : mImages.size();
        }


        public class ImgHolder extends RecyclerView.ViewHolder {
            @BindView(R.id.iv_img)
            ImageView ivImg;
            View itemView;

            public ImgHolder(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
                this.itemView = itemView;
            }

            public void update(int position) {
                loadNetImg(ivImg,  addHost(mImages.get(position)));
            }
        }

        public class EmptyHolder extends RecyclerView.ViewHolder {
            View itemView;

            public EmptyHolder(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
                this.itemView = itemView;
            }

            public void update(int position) {

            }
        }

    }
}
